package com.sengmitnick.timelogger;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.ace.ability.AceAbility;
import ohos.app.Environment;
import ohos.utils.zson.ZSONObject;

import java.util.Base64;
import java.util.Objects;

public class MainAbility extends AceAbility {
    private static final String JS_MODULE = "default";
    private String icon = "unknown";
    private String name = "未知状态";
    private String color = "#007DFF";

    @Override
    public void onStart(Intent intent) {
        intent.setParam("window_modal", 3);
        setInstanceName(JS_MODULE);

        Object businessInfo = Objects.requireNonNull(intent.getParams()).getParam("businessInfo");
        if (businessInfo != null) {
            ZSONObject businessInfoZSON = ZSONObject.classToZSON(businessInfo);
            // data91 is your device sn in nfc tag.
            String data91 = businessInfoZSON.getZSONObject("params").getString("91");
            // device sn is used to check your device validity
            String deviceSn = base64Decoder(data91);
            try {
                ZSONObject productParam = ZSONObject.stringToZSON(deviceSn);
                icon = productParam.getString("i");
                name = productParam.getString("n");
                color = productParam.getString("c");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        IntentParams intentParams = intent.getParams();

        if (intentParams != null) {
            intentParams.setParam("icon", icon);
            intentParams.setParam("name", name);
            intentParams.setParam("color", color);
            setPageParams(null, intentParams);
        }
        super.onStart(intent);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private String base64Decoder(String data91) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(data91);
        String str = "{}";
        try {
            str = new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
}
